package com.xunwulian.web.controller.buss;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.xunwulian.api.dto.BaseResponse;
import com.xunwulian.api.iface.*;
import com.xunwulian.base.constant.CmebEntity;
import com.xunwulian.base.constant.CommonErrorCode;
import com.xunwulian.base.entity.AppEntity;
import com.xunwulian.base.entity.CardInfoEntity;
import com.xunwulian.base.entity.Page;
import com.xunwulian.base.entity.User;
import com.xunwulian.base.util.DateStyle;
import com.xunwulian.base.util.FileUtil;
import com.xunwulian.base.util.PageData;
import com.xunwulian.base.util.UserUtil;
import com.xunwulian.web.controller.BaseController;
import com.xunwulian.web.entity.CardInfoEntityWrapper;
import com.xunwulian.web.util.Const;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/cardinfo")
public class CardInfoController extends BaseController {

    String menuUrl = "cardinfo/list.do"; // 菜单地址(权限用)

    @Reference
    private AppAPI appAPI;
    @Reference
    private CmebAPI cmebAPI;
    @Reference
    private CardAPI cardAPI;
    @Reference
    private ConfigAPI configAPI;
    @Reference
    private UserAPI userAPI;

    /**
     * 实时信息查询
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/now")
    public ModelAndView now(String msisdn) {
        ModelAndView mv = this.getModelAndView();

        try {
            PageData pd = this.getPageData();
            logger.info("pd:" + new Gson().toJson(pd));

            String msg = "";

            // 从session获取用户信息
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);

            CmebEntity cmeb = new CmebEntity();

            if (msisdn != null) {
                CardInfoEntity cardInfoEntity = cardAPI.getByMsisdn(msisdn);

                if (cardInfoEntity == null) {
                    msg = "卡号不存在！";
                } else if (!UserUtil.isSubAdmin(user.getROLE_ID()) && !UserUtil.isAdmin(user.getROLE_ID()) && !user.getUSER_ID().equals(cardInfoEntity.getUserId()) && !user.getUSER_ID().equals(cardInfoEntity.getUserId())) {

                    msg = "您无权查询该物联卡，请联系管理员设置权限！";
                } else {
                    AppEntity appEntity = (AppEntity) appAPI.getApp(cardInfoEntity.getAppId()).getData();
                    BaseResponse response = cmebAPI.queryCardInfo(msisdn, appEntity);
                    if (CommonErrorCode.SUCCESS.getType().equals(response.getCode())) {
                        cmeb = (CmebEntity) response.getData();
                    } else {
                        msg = response.getMsg();
                    }
                }
            }

            mv.setViewName("system/cardinfo/now");
            mv.addObject("msg", msg);
            mv.addObject("cmeb", cmeb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }


    /**
     * 列表
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(@Param("page") Page page,
                             @Param("msisdnKey") String msisdnKey,
                             @Param("userNameKey") String userNameKey) {

        logger.info("page:" + new Gson().toJson(page) + ", msisdnKey:" + msisdnKey + ", userNameKey:" + userNameKey);

        if (msisdnKey != null && !"".equals(msisdnKey)) {
            msisdnKey = msisdnKey.trim();
        }

        if (userNameKey != null && !"".equals(userNameKey)) {
            userNameKey = userNameKey.trim();
        }

        ModelAndView mv = this.getModelAndView();

        try {
            // 从session获取用户信息
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);

            // 管理员查询所有
            String userId = UserUtil.isAdmin(user.getROLE_ID()) || UserUtil.isSubAdmin(user.getROLE_ID()) ? "" : user.getUSER_ID();
            String appId = UserUtil.isSubAdmin(user.getROLE_ID()) ? user.getAppId() : "";

            BaseResponse response = cardAPI.listPage(page, appId, userId, msisdnKey, userNameKey);
            List<CardInfoEntity> varList = (List<CardInfoEntity>) response.getData();
            page = response.getPage();

            List<CardInfoEntityWrapper> listWrapper = varList.stream().map(entity -> new CardInfoEntityWrapper(entity)).collect(Collectors.toList());

            mv.addObject("varList", listWrapper);

            mv.setViewName("system/cardinfo/cardinfo_list");
            mv.addObject("msisdnKey", msisdnKey);
            mv.addObject("userNameKey", userNameKey);
            mv.addObject("page", page);
            mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mv;
    }

    /**
     * 跳转到新增
     */
    @RequestMapping(value = "/goAddC")
    public ModelAndView goAddU() {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        mv.addObject("msg", "saveC");
        mv.addObject("pd", pd);
        mv.setViewName("system/cardinfo/cardinfo_add");

        return mv;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/saveC")
    public ModelAndView saveU(PrintWriter out) {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();

        User user = (User) session.getAttribute(Const.SESSION_USER);
        String appId = user.getAppId();

        String content = pd.getString("CONTENT");
        String msisdnList[] = StringUtils.trimAllWhitespace(content).split(",");
        for (String msisdn : msisdnList) {
            cardAPI.addMsisdn(msisdn, appId, user);
        }

        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/download")
    public void download(HttpServletResponse response, String msisdnKey, String userNameKey) {
        try {
            // 从session获取用户信息
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);

            // 管理员查询所有
            String userId = UserUtil.isAdmin(user.getROLE_ID()) || UserUtil.isSubAdmin(user.getROLE_ID()) ? "" : user.getUSER_ID();
            // 只有二级管理员，限制平台
            String appId = UserUtil.isSubAdmin(user.getROLE_ID()) ? user.getAppId() : "";

            BaseResponse rpcResponse = cardAPI.listPage(null, appId, userId, msisdnKey, userNameKey);
            List<CardInfoEntity> cis = (List<CardInfoEntity>) rpcResponse.getData();

            LinkedHashMap<String, String> names = new LinkedHashMap<>();
            names.put("msisdn", "卡号");
            names.put("appId", "平台ID");
            names.put("appName", "平台名称");
            names.put("status", "卡状态");
            names.put("workStatus", "卡工作状态");
            names.put("gprs", "当月GPRS使用量");
            names.put("pkg", "移动套餐");
            names.put("userPkg", "用户套餐");
            names.put("userPrice", "用户按年价格");
            names.put("authSms", "预授权短信数");
            names.put("sms", "当月短信使用量");
            names.put("usedSms", "累计使用的短信量");


            String filename = "卡信息_" + DateFormatUtils.format(new Date(), DateStyle.YYYYMMDDHHMMSS.getValue()) + "_" + user.getUSERNAME() + ".xls";

            downloadExcel(response, configAPI.getByCode(Const.UPLOAD_PATH).getValue(), filename, cis, names);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 卡号导入
     *
     * @return
     */
    @RequestMapping("cardImport")
    public ModelAndView cardImport() {
        PageData pd = getPageData();
        ModelAndView mav = new ModelAndView("system/cardinfo/cardImport");

        List<User> userList = userAPI.listAll();
        mav.addObject("userList", userList);

        BaseResponse<List<AppEntity>> result = appAPI.getAppList();
        mav.addObject("varList", result.getData());

        mav.addObject("msg", pd.get("msg"));

        return mav;
    }

    /**
     * 上传文件
     */
    private String uploadFile(MultipartFile multipartFile, String saveFilePath) {
        try {
            FileUtil fileUtil = new FileUtil();
            // 获取文件的文件名
            String fileName = fileUtil.createFileName(multipartFile.getOriginalFilename());
            // 创建保存文件的根目录
            fileUtil.createFileDirectory(saveFilePath);
            File targetFile = new File(saveFilePath, fileName);
            //保存
            multipartFile.transferTo(targetFile);
            return targetFile.getCanonicalPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传
     */
    @RequestMapping(value = "uploadCard", method = RequestMethod.POST)
    public ModelAndView uploadCard(MultipartFile multipartFile, String appId, String userId, HttpServletRequest request) {
        try {
            String saveFilePath = request.getSession().getServletContext().getRealPath(configAPI.getByCode(Const.UPLOAD_PATH).getValue());

            FileUtil fileUtil = new FileUtil();
            // 获取文件的文件名
            String fileName = fileUtil.createFileName(multipartFile.getOriginalFilename());
            // 创建保存文件的根目录
            fileUtil.createFileDirectory(saveFilePath);
            File targetFile = new File(saveFilePath, fileName);
            //保存
            multipartFile.transferTo(targetFile);
            String targetFileName = targetFile.getCanonicalPath();
//            String targetFileName = uploadFile(multipartFile, saveFilePath);
            logger.info("saveFilePath:" + saveFilePath + ", targetFileName:" + targetFileName + ", appId:" + appId + ", userId:" + userId);

            User user = userAPI.getByUid(userId);
            cardAPI.parse2db(targetFileName, appId, user);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ModelAndView redirMV = new ModelAndView("redirect:/cardinfo/cardImport");
        redirMV.addObject("msg", "上传成功");

        return redirMV;

    }

    /**
     * @return
     */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }


    /**
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,
                true));
    }

}
